package org.sbbs.app.license.webapp.action;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.sbbs.app.license.model.CustomerInfo;
import org.sbbs.app.license.model.License;
import org.sbbs.app.license.model.LicenseInfo;
import org.sbbs.app.license.model.Product;
import org.sbbs.app.license.model.ProductInfo;
import org.sbbs.app.license.model.VenderInfo;
import org.sbbs.app.license.service.CustomerInfoManager;
import org.sbbs.app.license.service.HaspException;
import org.sbbs.app.license.service.HaspService;
import org.sbbs.app.license.service.LicenseInfoManager;
import org.sbbs.app.license.service.ProductInfoManager;
import org.sbbs.app.license.service.VenderInfoManager;
import org.sbbs.app.license.service.impl.HaspServiceImpl;
import org.sbbs.base.webapp.action.BaseGridAction;

public class HaspDogLicenseMaintainAction
    extends BaseGridAction {

    @Override
    public void prepare()
        throws Exception {
        this.venderInfo = this.VenderInfoManager.getVenderInfo();
        this.allProducts = this.ProductInfoManager.findAll();
        this.allEnabledProducts = this.ProductInfoManager.findAll();
    }

    public String addNew() {
        CustomerInfo cust = this.customerInfoManager.find( customerId );
        license = new License();
        license.setCustomer( cust.getCustomerName() );
        license.setVersionNumber( venderInfo.getVenderName() );
        license.setCopyrightInfo( venderInfo.getCopyRightInfo() );
        // license.setProducts( this.initProductFromProductInfo( allEnabledProducts ) );
        return SUCCESS;
    }

    public String gridPageList() {
        // Search search = PropertySearchBuilder.BuildSearch( getRequest() );
        // search.addFilterEqual( "venderInfo.venderId", vender.getVenderId() );
        // SearchResult srt = this.productInfoManager.searchAndCount( search );

        this.setPageList( this.initProductFromProductInfo( allEnabledProducts ) );
        /*
         * this.records = srt.getTotalCount(); this.total = getTotlePage( records, search.getMaxResults() ); this.page =
         * search.getPage() + 1;
         */
        return SUCCESS;
    }

    public String saveLicense() {
        License lic = this.genLicenseFromPost();

        try {
            String licString = this.haspService.genLicenseDefine( lic );
            String srcC2V = null;
            int lcount = this.LicenseInfoManager.getLicenseInfoCount( customerId );
            if ( lcount > 0 ) {
                LicenseInfo li = this.LicenseInfoManager.getCurrentUsedLicenseInfo( customerId );
                if ( li != null ) {
                    srcC2V = li.getInitC2VData();
                }
                else {
                    this.setAjaxMessage( getText( "error.common", new String[] { "此客户License数目大于1,但是没有正在使用的License,请检查." } ) );
                    this.setAjaxStatus( AJAX_STATUS_ERROR );
                    return ERROR;
                }

            }
            else {

                try {
                    srcC2V = this.haspService.getHaspInfo();
                }
                catch ( HaspException e ) {
                    e.printStackTrace();
                    this.setAjaxMessage( getText( "error.common", new String[] { "此客户License数目为0,但是在读取Dog中的License信息出错,请检查是否软件狗是否安装正确." } ) );
                    this.setAjaxStatus( AJAX_STATUS_ERROR );
                    return ERROR;
                }
            }

            String licV2c = this.haspService.genNewLicense( licString, srcC2V );

            LicenseInfo linfo = new LicenseInfo();
            linfo.setCustomerInfo( this.customerInfoManager.find( customerId ) );
            linfo.setGenDate( new Date() );
            linfo.setLicenseData( licV2c );
            linfo.setLicenseDefineData( licString );
            linfo.setInitC2VData( srcC2V );
            this.LicenseInfoManager.save( linfo );

            this.log.info( licString );
            this.log.info( srcC2V );
            this.log.info( licV2c );
            this.setAjaxMessage( "gen license success." );
            this.setAjaxStatus( AJAX_STATUS_SUCCESS );
        }
        catch ( Exception e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            this.setAjaxMessage( getText( "error.common", new String[] { e.getMessage() } ) );
            this.setAjaxStatus( AJAX_STATUS_ERROR );
            return ERROR;
        }
        return SUCCESS;
    }

    private Long licenseInfoId;

    public Long getLicenseInfoId() {
        return licenseInfoId;
    }

    public void setLicenseInfoId( Long licenseInfoId ) {
        this.licenseInfoId = licenseInfoId;
    }

    public String watchLicense() {
        try {
            LicenseInfo li = this.LicenseInfoManager.find( licenseInfoId );

            License lic = this.haspService.parseFromLicenseInfo( li );

            lic.setProducts( this.ProductInfoManager.fitProducts( lic.getProducts() ) );
            this.license = lic;

            this.log.info( li.getLicenseData() );
            String decodeInfo = haspService.decodeHaspInfo( li.getInitC2VData() );
            this.log.info( decodeInfo );
            // this.setAjaxMessage( "load license success." );
            // this.setAjaxStatus( AJAX_STATUS_SUCCESS );
            return SUCCESS;
        }
        catch ( HaspException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            this.setAjaxMessage( getText( "error.common", new String[] { e.getMessage() } ) );
            this.setAjaxStatus( AJAX_STATUS_ERROR );
            return this.ERROR;
        }
    }

    public String watchDogLicense() {
        try {
            String info = haspService.getHaspInfo();
            String decodeInfo = haspService.decodeHaspInfo( info );
            License lic = this.haspService.parseFromDogInfo( decodeInfo );
            lic.setProducts( this.ProductInfoManager.fitProducts( lic.getProducts() ) );
            log.info( info );
            log.info( decodeInfo );
            this.license = lic;
        }
        catch ( HaspException e ) {
            e.printStackTrace();
            this.setAjaxMessage( getText( "error.common", new String[] { e.getMessage() } ) );
            this.setAjaxStatus( AJAX_STATUS_ERROR );
            return this.ERROR;
        }
        return SUCCESS;
    }

    public String updateDog() {
        try {
            LicenseInfo li = this.LicenseInfoManager.find( licenseInfoId );
            String v2c = li.getLicenseData();
            String rn = this.haspService.updateLicenseToDog( v2c );

            String info = haspService.getHaspInfo();
            // li.setCurrentUsed( true );
            li.setInitC2VData( info );
            this.LicenseInfoManager.save( li );

            this.LicenseInfoManager.updateCurrentLicense( li.getLicenseInfoId() );

            this.setAjaxMessage( "update  license to hasp dog  success." );
            this.setAjaxStatus( AJAX_STATUS_SUCCESS );
            return SUCCESS;
        }
        catch ( HaspException e ) {
            e.printStackTrace();
            this.setAjaxMessage( getText( "error.common", new String[] { e.getMessage() } ) );
            this.setAjaxStatus( AJAX_STATUS_ERROR );
            return this.ERROR;
        }
    }

    public String updateCurrentLicenseInfo() {
        this.LicenseInfoManager.updateCurrentLicense( this.licenseInfoId );
        this.setAjaxMessage( "设置当前使用License成功." );
        this.setAjaxStatus( AJAX_STATUS_SUCCESS );
        return SUCCESS;
    }

    private String licenseIds;

    public String getLicenseIds() {
        return licenseIds;
    }

    public void setLicenseIds( String licenseIds ) {
        this.licenseIds = licenseIds;
    }

    public String deleteLicense() {
        String[] sIds = this.licenseIds.split( "," );

        Long[] lIds = new Long[sIds.length];
        for ( int i = 0; i < sIds.length; i++ ) {
            lIds[i] = Long.parseLong( sIds[i] );
        }

        LicenseInfo culic = this.LicenseInfoManager.getCurrentUsedLicenseInfo( customerId );

        boolean find = false;
        if ( culic != null )
            for ( int i = 0; i < lIds.length; i++ ) {
                if ( lIds[i] == culic.getLicenseInfoId() ) {
                    find = true;
                    break;
                }
            }
        if ( find ) {
            this.setAjaxMessage( "不能删除当前使用中的License." );
            this.setAjaxStatus( AJAX_STATUS_ERROR );
            return ERROR;
        }
        else {

            this.LicenseInfoManager.removeByIds( lIds );
            this.setAjaxMessage( "设置当前使用License成功." );
            this.setAjaxStatus( AJAX_STATUS_SUCCESS );
            return SUCCESS;
        }
    }

    public String outputLicenseV2C() {
        try {
            
            
            LicenseInfo li = this.LicenseInfoManager.find( licenseInfoId );
            SimpleDateFormat   df = new SimpleDateFormat("yyyy_MM_dd");
            String returnValue = df.format(li.getGenDate());
            
            String title = li.getCustomerInfo().getCustomerName()+"_"+returnValue+".v2c";
            HttpServletResponse resp = this.getResponse();
            resp.setContentType( "text/xml" );
            resp.setHeader( "Content-Disposition", "attachment;filename=" + new String( title.getBytes("UTF-8"), "ISO8859-1" ) );// "ISO8859-1"

            OutputStream outs;
            outs = resp.getOutputStream();
            outs.write( li.getLicenseData().getBytes() );
            
            outs.flush();
            outs.close();
        }
        catch ( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return
     */
    private License genLicenseFromPost() {
        String allpram = this.getRequest().getParameter( "allParam" );

        CustomerInfo cust = this.customerInfoManager.find( customerId );
        license = new License();
        license.setCustomer( cust.getCustomerName() );
        license.setVersionNumber( venderInfo.getVenderName() );
        license.setCopyrightInfo( venderInfo.getCopyRightInfo() );
        license.setProducts( this.initProductFromPost( allpram ) );
        return license;
    }

    private List<Product> initProductFromPost( String allpram ) {
        String[] allParams = allpram.split( ";" );
        List<Map> entityMap = new ArrayList<Map>();
        for ( int i = 0; i < allParams.length; i++ ) {
            String[] ps = allParams[i].split( "\\|" );
            Map map = new HashMap();
            for ( int j = 0; j < ps.length; j++ ) {
                String[] coms = ps[j].split( ":" );
                map.put( coms[0], coms[1] );
            }

            String key = ps[ps.length - 1];
            entityMap.add( map );
        }
        List<Product> pl = new ArrayList<Product>();
        for ( Iterator iterator = entityMap.iterator(); iterator.hasNext(); ) {
            Map map = (Map) iterator.next();

            Product pro = new Product();
            pro.setProductId( (String) map.get( "id" ) );
            pro.setProductName( this.ProductInfoManager.find( pro.getProductId() ).getProductName() );
            pro.setAllowedUsers( (String) map.get( "allowedUsers" ) );
            pl.add( pro );

        }

        return pl;
    }

    private List<Product> initProductFromProductInfo( List<ProductInfo> l ) {
        List<Product> pl = new ArrayList<Product>();
        for ( Iterator iterator = l.iterator(); iterator.hasNext(); ) {
            ProductInfo info = (ProductInfo) iterator.next();
            Product pro = new Product();
            pro.setProductId( info.getProductId() );
            pro.setProductName( info.getProductName() );
            pro.setAllowedUsers( "-1" );
            pl.add( pro );
        }
        return pl;
    }

    private License license = null;

    private Long customerId = null;

    private VenderInfo venderInfo = null;

    // private CustomerInfo customerInfo = null;

    private List<ProductInfo> allProducts = null;

    private List<ProductInfo> allEnabledProducts = null;

    private VenderInfoManager VenderInfoManager;

    private ProductInfoManager ProductInfoManager;

    private CustomerInfoManager customerInfoManager;

    private LicenseInfoManager LicenseInfoManager;

    private HaspService haspService = new HaspServiceImpl();

    public License getLicense() {
        return license;
    }

    public void setLicense( License license ) {
        this.license = license;
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId( Long customerId ) {
        this.customerId = customerId;
    }

    public CustomerInfoManager getCustomerInfoManager() {
        return customerInfoManager;
    }

    public void setCustomerInfoManager( CustomerInfoManager customerInfoManager ) {
        this.customerInfoManager = customerInfoManager;
    }

    public VenderInfoManager getVenderInfoManager() {
        return VenderInfoManager;
    }

    public void setVenderInfoManager( VenderInfoManager venderInfoManager ) {
        VenderInfoManager = venderInfoManager;
    }

    public ProductInfoManager getProductInfoManager() {
        return ProductInfoManager;
    }

    public void setProductInfoManager( ProductInfoManager productInfoManager ) {
        ProductInfoManager = productInfoManager;
    }

    public LicenseInfoManager getLicenseInfoManager() {
        return LicenseInfoManager;
    }

    public void setLicenseInfoManager( LicenseInfoManager licenseInfoManager ) {
        LicenseInfoManager = licenseInfoManager;
    }

    /*
     * public HaspService getHaspService() { return haspService; } public void setHaspService( HaspService haspService )
     * { this.haspService = haspService; }
     */

    /*
     * @Override public String gridPageList() { // TODO Auto-generated method stub return null; }
     */

}
